package cn.zebra.dev.admin.module.security.entity;

import cn.zebra.dev.base.module.admin.entity.BaseAdmin;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.util.CollectionUtils;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

/**
 * @author runnable@sina.cn
 */
public class AdminDetailsEntity implements UserDetails {
    /**
     * 后台用户信息
     */
    private BaseAdmin admin;

    /**
     * 用户绑定角色id
     */
    private Collection<Long> roleIds;

    private Boolean accountNonExpired;

    private Boolean enabled;

    private Boolean credentialsNonExpired;

    private Boolean accountNonLocked;

    public AdminDetailsEntity(BaseAdmin admin) {
        this.admin = admin;
        this.enabled = admin.getStatus() != -1;
        this.accountNonLocked = true;
        this.accountNonExpired = true;
        this.credentialsNonExpired = true;
        this.roleIds = admin.getRoleIds();
    }

    @Override
    public Collection<? extends GrantedAuthority> getAuthorities() {
        List<GrantedAuthority> grantedAuthorities = new ArrayList<>();
        if (!CollectionUtils.isEmpty(this.roleIds)) {
            for (Long roleId : this.roleIds) {
                SimpleGrantedAuthority authority = new SimpleGrantedAuthority(roleId.toString());
                grantedAuthorities.add(authority);
            }
        }
        return grantedAuthorities;
    }

    @Override
    public String getPassword() {
        return this.admin.getPassword();
    }

    @Override
    public String getUsername() {
        return this.admin.getAdminName();
    }

    @Override
    public boolean isAccountNonExpired() {
        return accountNonExpired;
    }

    @Override
    public boolean isAccountNonLocked() {
        return accountNonLocked;
    }

    @Override
    public boolean isCredentialsNonExpired() {
        return credentialsNonExpired;
    }

    @Override
    public boolean isEnabled() {
        return enabled;
    }

    public void setAdmin(BaseAdmin admin) {
        this.admin = admin;
    }

    public BaseAdmin getAdmin() {
        return this.admin;
    }
}